package cn.iocoder.springboot.lab03.kafkademo.crane;

import cn.iocoder.springboot.lab03.kafkademo.Dao.ItemDao;
import cn.iocoder.springboot.lab03.kafkademo.entity.Po.Item;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @Author：YH
 * @Description：
 * @Date:Created in 2023/12/17 13:48
 */
@Component
@EnableScheduling
@Slf4j
public class Schedule {
    @Resource
    private ItemDao itemDao;
    @Resource
    private RedisTemplate<Integer, Item> redisTemplate;

    private static Cache<Integer, Item> cache = CacheBuilder
            .newBuilder()
            .expireAfterWrite(20, TimeUnit.SECONDS)
            .build();

    @Scheduled(cron = "0/1 * * * * ?")
    public void refreshDataFromDb() {
        List<Item> itemPos = (List<Item>) itemDao.readAllItemData();
//        log.info("[refreshDataFromDb]:{}", itemPos);
//        //塞入本地缓存
//        itemPos.stream().map(x -> {
//            cache.put(x.getId(), x);
//            return null;
//        }).collect(Collectors.toList());
        //塞入分布式缓存
//        itemPos.stream().map(x -> {
//            redisTemplate.opsForValue().set(x.getId(), x, 30, TimeUnit.SECONDS);
//            return null;
//        }).collect(Collectors.toList());
    }

    public Item getIntermFromCacheAndDb(Integer id) throws ExecutionException {
        return getItemInfoFromRedisAndDb(id);
//        //从guava本地缓存中获取数据,如果没有则从redis中回源
//        Item item = cache.get(id, new Callable<Item>() {
//            @Override
//            public Item call() throws Exception {
//                log.info("本地缓存没有数据，从分布式缓存读取数据");
//                return getItemInfoFromRedisAndDb(id);
//            }
//        });
//        if (Objects.nonNull(item)) {
//            return item;
//        }
//        return null;
    }

    public Item getItemInfoFromRedisAndDb(Integer id) {
        Item item = null;
        item = redisTemplate.opsForValue().get(id);
        if (Objects.isNull(item)) {
            log.info("从数据库读数据");
            Item intemFromDb = itemDao.selectByPrimaryKey(id);
            redisTemplate.opsForValue().set(id, intemFromDb, 10, TimeUnit.SECONDS);
            return intemFromDb;
        }
        log.info("分布式缓存有数据，直接读取分布式缓存数据");
        return item;
    }
}
